import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/Login'
import Reg from '@/views/Reg/Reg'
import Main from '@/views/Main/Main'
import store from '../store/index'
import { Message } from 'element-ui'
import Home from '@/views/menus/Home/Home'
import UserInfo from '@/views/menus/user/userInfo/UserInfo'
import UserAvatar from '../views/menus/user/UserAvatar/UserAvatar'
import UserPwd from '../views/menus/user/UserPwd/UserPwd'
import ArtCate from '../views/menus/Article/ArtCate'
import ArtList from '../views/menus/Article/ArtList'

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/login', component: Login },
  { path: '/reg', component: Reg },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }

]

const router = new VueRouter({

  routes
})
// 配置路由前置守卫 ：验证是否有token 才能去到首页，不然只能去到登录或注册页
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 设置白名单
  const whiteList = ['/login', '/reg']
  if (!token && !whiteList.includes(to.path)) {
    next('/login')
    // 提示用户没有登录
    Message.error('您还没有登录')
  } else {
    next()
  }
})
export default router
